#include "IOServicePool.h"

IOServicePool::IOServicePool(const size_t size) : _io_contexts(size), _works(size),
                                                  _next_io_context(0) {
    //每个io_context都分给一个work进行管理
    for (int i = 0; i < size; i++) {
        _works[i] = std::make_unique<io_context::work>(_io_contexts[i]);
    }

    //创建线程，每个线程分配一个io_context
    for (int i = 0; i < size; i++) {
        _threads.emplace_back([this, i]() {
            _io_contexts[i].run();
        });
    }
}

IOServicePool::~IOServicePool() {
    Stop();
    clog << "IOServicePool destruct" << endl;
}

// 使用 round-robin 的方式返回一个 io_service
io_context& IOServicePool::GetIOService() {
    auto& io_context = _io_contexts[_next_io_context++];
    if (_next_io_context == _io_contexts.size()) {
        _next_io_context = 0;
    }
    return io_context;
}

void IOServicePool::Stop() {
    for (auto& work : _works) {
        //把服务先停止
        work->get_io_context().stop();
        work.reset();
    }
    //阻塞每个线程等待最后的任务结束
    for (auto& thread : _threads) {
        thread.join();
    }
}
